<?php namespace App\Http\Middleware;

use Closure;
use App\Models\Users;
use App\Models\Employee;

class AspxkeyMiddleware {

	public function __construct()
	{
	}
	/**
	 * Handle an incoming request.
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request,Closure $next)
	{
		$user=array();$v=empty($request['v'])?$request['V']:$request['v'];$user=array();
		$Account=$request['account'];$Password=$request['password'];
		if( $v==1.0 )
		{
			$user = Users::where(array('username'=>$Account,'userpass'=>md5($Password)))->first();
			if( $user )
			{
				if( !empty($user->bindip) && !strstr($user->bindip,$request->getClientIp()) )
				{
					$user=array();//有IP验证的对IP进行验证
					return response(array('Code'=>'001','Message'=>'IP被拒绝'), HTTP_NOLOGIN);
				}
			}
			else
				return response(array('Code'=>'003','Message'=>'帐号密码错误'), HTTP_NOLOGIN);
		}
		elseif( $v==1.1 )
		{
			$user = Users::where(array('username'=>$Account))->first();
			if( $user )
			{
				$apikey=$user->apikey;
				if( !empty($user->bindip) && !strstr($user->bindip,$request->getClientIp()) )
				{
					$user=array();//有IP验证的对IP进行验证
					return response(array('Code'=>'001','Message'=>'IP被拒绝'), HTTP_NOLOGIN);
				}
				else
				{
					//http://host.com/api.aspx?v=1.1&action=charge&account=帐号&mobile=手机号&package=100&sign=MD5
					//http://host.com/api.aspx?v=1.1&action=getPackage&account=帐号&sign=MD5
					//http://host.com/api.aspx?v=1.1&action=getBalance&account=帐号&sign=MD5
					//http://host.com/api.aspx?v=1.1&action=getReports&account=帐号&sign=MD5
					if( $request['action']=='charge' )
					{
						$Sign=md5("account=".$Account."&mobile=".$request['mobile']."&package=".$code."&key=".$user->apikey);
					}
					elseif( $request['action']=='getPackage' )
					{
						$Sign=md5("account=".$Account."&type=".$request['type']."&key=".$user->apikey);
					}
					elseif( $request['action']=='getBalance' )
					{
						$Sign=md5("account=".$Account."&key=".$user->apikey);
					}
					elseif( $request['action']=='getReports' )
					{
						$Sign=md5("account=".$Account."&count=".$request['count']."&key=".$user->apikey);
					}
					if( $Sign!=$request['sign'] )
					{
						$user=array();
						return response(array('Code'=>'003','Message'=>'签名验证错误'), HTTP_NOLOGIN);
					}
				}
			}
			else
				return response(array('Code'=>'001','Message'=>'参数错误'), HTTP_NOLOGIN);
		}
		$request->user=$user;
		return ( $user ) ? $next($request): response(array('Code'=>'010','Message'=>'协议版本错误'), HTTP_NOLOGIN);
	}

}
// 0操作成功
// 001参数错误
// 002充值号码不合法
// 003帐号密码错误
// 004余额不足
// 005不存在指定流量包
// 006不支持该地区
// 007卡号或者密码错误
// 008该卡已使用过
// 009该卡不支持(移动/电信/联通)号码
// 010协议版本错误
// 999其他错误

